import React, { useEffect, useState, useCallback } from 'react';
import { Select, Button, Modal, Form, Input, InputNumber, message, Tag, Space } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { getProductTagList, createProductTag } from '@/services/ant-design-pro/product';

interface ProductTagSelectorProps {
    value?: string[];
    onChange?: (value: string[]) => void;
    [key: string]: any; // 允许其他属性传递
}

interface TagItem {
    id: string;
    name: string;
    status: number;
    sort: number;
}

const ProductTagSelector: React.FC<ProductTagSelectorProps> = ({ value = [], onChange }) => {
    const [tags, setTags] = useState<TagItem[]>([]);
    const [loading, setLoading] = useState(false);
    const [modalVisible, setModalVisible] = useState(false);
    const [form] = Form.useForm();
    const [searchValue, setSearchValue] = useState('');
    const [hasMore, setHasMore] = useState(true);
    const [currentPage, setCurrentPage] = useState(1);
    const [searchLoading, setSearchLoading] = useState(false);
    const pageSize = 100;

    // 防抖搜索函数
    const debouncedSearch = useCallback(
        (() => {
            let timeoutId: NodeJS.Timeout;
            return (value: string) => {
                clearTimeout(timeoutId);
                timeoutId = setTimeout(() => {
                    handleSearch(value);
                }, 300); // 300ms 防抖延迟
            };
        })(),
        []
    );

    // 获取标签列表
    const fetchTags = async (page = 1, search = '') => {
        if (page === 1) {
            setSearchLoading(true);
        } else {
            setLoading(true);
        }
        
        try {
            const response = await getProductTagList({ 
                page, 
                pageSize,
                keyword: search || undefined
            });
            
            if (response?.data?.list) {
                if (page === 1) {
                    setTags(response.data.list);
                } else {
                    setTags(prev => [...prev, ...response.data.list]);
                }
                setHasMore(response.data.list.length === pageSize);
                setCurrentPage(page);
            }
        } catch (error) {
            message.error('获取标签列表失败');
        } finally {
            if (page === 1) {
                setSearchLoading(false);
            } else {
                setLoading(false);
            }
        }
    };

    // 搜索标签
    const handleSearch = (value: string) => {
        setSearchValue(value);
        setCurrentPage(1);
        setHasMore(true);
        fetchTags(1, value);
    };

    // 处理搜索输入
    const handleSearchInput = (value: string) => {
        setSearchValue(value);
        if (value.trim()) {
            debouncedSearch(value);
        } else {
            // 如果搜索框为空，重新加载所有标签
            setCurrentPage(1);
            setHasMore(true);
            fetchTags(1, '');
        }
    };

    // 加载更多标签
    const handlePopupScroll = (e: React.UIEvent<HTMLDivElement>) => {
        const { target } = e;
        const { scrollTop, scrollHeight, clientHeight } = target as HTMLDivElement;
        
        if (scrollTop + clientHeight >= scrollHeight - 5 && !loading && !searchLoading && hasMore) {
            fetchTags(currentPage + 1, searchValue);
        }
    };

    // 创建新标签
    const handleCreateTag = async (values: any) => {
        try {
            const response = await createProductTag({
                name: values.name,
                status: values.status || 1, // 默认启用
                sort: values.sort || 0
            });
            
            if (response?.code === 1) {
                message.error('创建标签失败');
                return;
            }
            
            message.success('创建标签成功');
            setModalVisible(false);
            form.resetFields();
            
            // 重新获取标签列表
            setCurrentPage(1);
            setHasMore(true);
            fetchTags(1, searchValue);
        } catch (error) {
            message.error('创建标签失败');
        }
    };

    // 处理标签选择变化
    const handleTagChange = (selectedTags: string[]) => {
        onChange?.(selectedTags);
    };

    // 移除标签
    const handleRemoveTag = (tagId: string) => {
        const newValue = value.filter(id => id !== tagId);
        onChange?.(newValue);
    };

    useEffect(() => {
        fetchTags(1);
    }, []);

    const selectedTags = tags.filter(tag => value.includes(tag.id));

    return (
        <div>
            <Space direction="vertical" style={{ width: '100%' }}>
                <Select
                    mode="multiple"
                    placeholder="请选择商品标签"
                    value={value}
                    onChange={handleTagChange}
                    loading={loading || searchLoading}
                    style={{ width: '100%' }}
                    options={tags.map(tag => ({
                        label: tag.name,
                        value: tag.id,
                        disabled: tag.status === 0
                    }))}
                    onSearch={handleSearchInput}
                    showSearch
                    filterOption={false}
                    onPopupScroll={handlePopupScroll}
                    notFoundContent={
                        searchLoading ? (
                            <div style={{ padding: '8px', textAlign: 'center', color: '#999' }}>
                                搜索中...
                            </div>
                        ) : searchValue && tags.length === 0 ? (
                            <div style={{ padding: '8px', textAlign: 'center', color: '#999' }}>
                                未找到相关标签
                            </div>
                        ) : null
                    }
                    dropdownRender={(menu) => (
                        <div>
                            {menu}
                            {hasMore && !searchLoading && (
                                <div style={{ padding: '8px', textAlign: 'center', color: '#999' }}>
                                    {loading ? '加载中...' : '滚动加载更多'}
                                </div>
                            )}
                            <div style={{ padding: '8px', borderTop: '1px solid #f0f0f0' }}>
                                <Button
                                    type="text"
                                    icon={<PlusOutlined />}
                                    onClick={() => setModalVisible(true)}
                                    style={{ width: '100%' }}
                                >
                                    添加新标签
                                </Button>
                            </div>
                        </div>
                    )}
                />
                
                {selectedTags.length > 0 && (
                    <div style={{ marginTop: 8 }}>
                        <span style={{ marginRight: 8, color: '#666' }}>已选标签：</span>
                        {selectedTags.map(tag => (
                            <Tag
                                key={tag.id}
                                closable
                                onClose={() => handleRemoveTag(tag.id)}
                                style={{ marginBottom: 4 }}
                            >
                                {tag.name}
                            </Tag>
                        ))}
                    </div>
                )}
            </Space>

            <Modal
                title="添加新标签"
                open={modalVisible}
                onCancel={() => setModalVisible(false)}
                footer={null}
            >
                <Form
                    form={form}
                    onFinish={handleCreateTag}
                    layout="vertical"
                >
                    <Form.Item
                        name="name"
                        label="标签名称"
                        rules={[{ required: true, message: '请输入标签名称' }]}
                    >
                        <Input placeholder="请输入标签名称" />
                    </Form.Item>
                    
                    <Form.Item
                        name="status"
                        label="状态"
                        initialValue={1}
                    >
                        <Select>
                            <Select.Option value={0}>禁用</Select.Option>
                            <Select.Option value={1}>启用</Select.Option>
                        </Select>
                    </Form.Item>
                    
                    <Form.Item
                        name="sort"
                        label="排序"
                        initialValue={0}
                    >
                        <InputNumber min={0} style={{ width: '100%' }} />
                    </Form.Item>
                    
                    <Form.Item>
                        <Space>
                            <Button type="primary" htmlType="submit">
                                确定
                            </Button>
                            <Button onClick={() => setModalVisible(false)}>
                                取消
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default ProductTagSelector; 